<template>
	<view class="container">
        <!-- 自定义导航栏 -->
        <custom-navbar :showTitle="false" title="修改个人信息" :isCoverNav="false" backgroundColor="#ffffff" textColor="#000" :showBack="true"></custom-navbar>
		
		
		<!-- 头像区域 -->
		<view class="avatar-section">
			<view class="avatar-container">
				<image 
					:src="userInfo.avatar || defaultAvatar" 
					class="avatar-image"
					mode="aspectFill"
				/>
				<!-- 透明按钮覆盖头像 -->
				<button 
					class="avatar-button"
					open-type="chooseAvatar"
					@chooseavatar="onChooseAvatar"
					hover-class="none"
				></button>
			</view>
		</view>
		
		<!-- 昵称输入区域 -->
		<view class="nickname-section">
			<view class="input-group">
				<text class="label">昵称</text>
				<input 
					class="nickname-input"
					type="nickname"
					v-model="userInfo.nickname"
					placeholder="请输入昵称"
					placeholder-class="placeholder-style"
					@blur="onNicknameBlur"
				/>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { userSetInfoFun, userInfoFun } from '@/api/port'
import customNavbar from '../../components/custom-navbar/index.vue';
// 默认头像
const defaultAvatar = '/static/images/default-avatar.svg'

// 用户信息
const userInfo = reactive({
	avatar: '',
	nickname: ''
})

// 页面加载
onLoad((options) => {
	// 获取用户信息
	getUserInfo()
})

// 获取用户信息
const getUserInfo = () => {
	// 从缓存或接口获取用户信息
    userInfoFun().then(res => {
        if (res.code === 1) {
            userInfo.avatar = res.data.avatar || ''
            userInfo.nickname = res.data.nickname || ''
        }
    })
}

// 选择头像回调
const onChooseAvatar = async (e) => {
	console.log('选择头像:', e)
	const { avatarUrl } = e.detail
	if (avatarUrl) {
		try {
			// 这里可以调用上传头像的接口
			const uploadAvatarUrl = await uploadAvatar(avatarUrl)
            console.log(uploadAvatarUrl)
            if(uploadAvatarUrl.code == 1){
                userInfo.avatar = uploadAvatarUrl.data.uri
                userSetInfoFun({
                    field: 'avatar',
                    value: uploadAvatarUrl.data.uri
                }).then(res => {
                    if (res.code === 1) {
                        uni.showToast({
                            title: '上传成功',
                            icon: 'success',
                            duration: 2000
                        })
                    }
                })
            }
        } catch (error) {
            uni.showToast({
                title: '上传失败',
                icon: 'none',
                duration: 2000
            })
        }
	}
}

// 昵称输入失焦
const onNicknameBlur = (e) => {
	console.log('昵称输入:', e.detail.value)
	// 微信会自动进行安全检测，如果不通过会清空内容
    if(e.detail.value){
        userSetInfoFun({
            field: 'nickname',
            value: e.detail.value
        }).then(res => {
            if (res.code === 1) {
                uni.showToast({
                    title: '上传成功',
                    icon: 'success',
                    duration: 2000
                })
            }
        })
    }
}

// 上传头像
const uploadAvatar = (avatarUrl) => {
	// 这里实现头像上传逻辑
	console.log('上传头像:', avatarUrl)
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: 'https://client-hoteltool.shengxuankj.com/api/upload/image', // 仅为示例，非真实的接口地址
            filePath: avatarUrl,
            name: 'file',
            formData: {
                user: 'test',
            },
            header: {
                'Content-Type': 'multipart/form-data',
                'Token': uni.getStorageSync('token')
            },
            success: (res) => {
                console.log('上传成功:', res)
                try {
                    resolve(JSON.parse(res.data));
                } catch (error) {
                    reject(new Error('解析响应数据失败'));
                }
            },
            fail: (error) => {
                reject(new Error('图片上传失败: ' + error.errMsg));
            }
        });
    })
	// 可以调用后端接口上传头像
}

// 保存用户信息
const saveUserInfo = () => {
	// 保存到缓存
	uni.setStorageSync('userInfo', userInfo)
	// 调用后端接口保存
	console.log('保存用户信息:', userInfo)
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.avatar-section {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 80rpx 0 60rpx;
	background-color: #fff;
}

.avatar-container {
	position: relative;
	width: 200rpx;
	height: 200rpx;
}

.avatar-image {
	width: 100%;
	height: 100%;
	border-radius: 50%;
	background-color: #e5e5e5;
}

.avatar-button {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	border-radius: 50%;
	background-color: transparent;
	border: none;
	padding: 0;
	margin: 0;
	outline: none;
	
	&::after {
		border: none;
	}
}

.nickname-section {
	margin-top: 20rpx;
	background-color: #fff;
	padding: 0 40rpx;
}

.input-group {
	display: flex;
	align-items: center;
	padding: 40rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.label {
	font-size: 32rpx;
	color: #333;
	width: 120rpx;
	flex-shrink: 0;
}

.nickname-input {
	flex: 1;
	font-size: 32rpx;
	color: #333;
	padding: 0 20rpx;
	height: 80rpx;
	line-height: 80rpx;
}

.placeholder-style {
	color: #999;
}
</style>